package com.htjc.uep.center.acct.service.impl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.htjc.uep.center.acct.mapper.UpPoolConsumeWsgwMapper;
import com.htjc.uep.center.acct.service.IAcctService;
import com.htjc.uep.center.acct.utils.DateUtil;
import com.htjc.uep.center.commons.utils.IOUtil;
import com.htjc.uep.center.model.entity.FTPConfig;

import oracle.net.aso.s;

@Service
public class AcctServiceImpl implements IAcctService{

	private Logger log = LoggerFactory.getLogger(this.getClass());
	
	private FileChannel fileChannel;
	
	private WritableByteChannel byteChannel;
	
	private String pathSeparator = File.separator;
	
	private String dataSeparator = "|";
	
	private static final String encoding = "UTF-8";
	
	private ByteBuffer byteBuffer;
	
	private int byteCapacity = 100;
	
	@Value("${acct.filePath}")
	private String filePath;
	
	
	@Autowired
	private UpPoolConsumeWsgwMapper mapper;
	
	@Override
	public void getAcctDate(HttpServletResponse response, FTPConfig ftpConfig, String acctDate, String accountCode, String platformCode){
		
		OutputStream os = null;
		FileInputStream fileIn = null;
		ServletOutputStream out = null;
		
		FileOutputStream fileOut = null;
		BufferedOutputStream buffOut = null;
		
		try {
			
			log.info("积分对账-对账流服务开始-账务日期={},结算单位={}", acctDate, accountCode);
			
			
			String headler = mapper.queryUpPoolWsgw(platformCode, accountCode, acctDate);
			
			String fileName = "JF_POOL_" + platformCode + "_" + accountCode + "_" + acctDate + ".txt";
			
			filePath = filePath + pathSeparator + fileName;
			
			List<Map<String, Object>> consumeMap = mapper.queryConsume(platformCode, accountCode, acctDate);
			
			System.out.println(filePath);
			
			File file = new File(filePath);
			
			if (!file.exists()) {
				file.createNewFile();
			}
			fileOut = new FileOutputStream(file);
			buffOut = new BufferedOutputStream(fileOut);
			
			os = buffOut;
			
			String line = "\r\n";
			
			headler = headler + line;
			
			byte[] data = headler.getBytes("UTF-8");
			os.write(data, 0, data.length);
			os.flush();
			
			for (Map<String, Object> map : consumeMap) {
				
				String dealId = (String) map.get("businessId");
				String userId = (String) map.get("userId");
				
				BigDecimal scoreTmp = (BigDecimal) map.get("consumeNum");
				String score = scoreTmp.toString();
				
				String sendTime = (String) map.get("consumeTime");
				String status = (String) map.get("consumeStatus");
				
				String lineData = dealId + "|" + userId + "|" + score + "|" + sendTime + "|" + status;
				lineData = lineData + line;
				
				byte[] dataLine = lineData.getBytes("UTF-8");
				os.write(dataLine, 0, dataLine.length);
				os.flush();
			}
		
			os.close();
			buffOut.close();
			fileOut.close();
			
			out = response.getOutputStream();
			
			if (!file.exists()) {
				log.info("积分对账-对账文件不存在-路径={}", file.getPath());
				String notExists = "02" + dataSeparator + "0" + dataSeparator + "0" + dataSeparator + accountCode + dataSeparator + acctDate ;
				byte[] byteReponse = notExists.getBytes(encoding);
				out.write(byteReponse);
				out.flush();
				IOUtil.closeQuietly(out);
				return;
			}
			
			fileIn = new FileInputStream(file);
			fileChannel = fileIn.getChannel();
			byteChannel = Channels.newChannel(out);
			
			byteBuffer = ByteBuffer.allocate(byteCapacity);
			
			while(fileChannel.read(byteBuffer) != -1) {
				byteBuffer.flip();
				
				while (byteBuffer.hasRemaining()) {
					
					int lim = byteBuffer.limit();
					
					if (lim < byteCapacity) {
						byte[] bytes = new byte[lim];
						int i = 0;
						while (byteBuffer.hasRemaining()) {
							bytes[i] = byteBuffer.get();
							i++;
						}
						out.write(bytes);
						continue;
					} else {
					
						byte[] bytes = byteBuffer.array();
						out.write(bytes);
					}
					byteBuffer.position(lim);
				}
				byteBuffer.clear();
			}
			out.flush();
			log.info("积分对账-对账流服务完成");
		} catch (Exception e) {
			log.error("", e);
		} finally {
			IOUtil.closeQuietly(fileIn, fileChannel, byteChannel, out, os, buffOut, fileOut);
		}
	}
}



































